package main.pack;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.ListActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Toast;

public class ReadHoroscopeActivity extends ListActivity{
	
	HashMap<String,String> xmlDataA = new HashMap<String,String>();
	Document xml;
	public String signGetData;
	
	public void onCreate(Bundle savedInstanceState) 
	{

		super.onCreate(savedInstanceState);
		setContentView (R.layout.read);
       
		//catch accidental disk or network access on the app's main thread, 
		//where UI operations are received and animations take place
    	StrictMode.enableDefaults();
    	
     
    	// get sign name
		Bundle extras = getIntent().getExtras();
		
        if(extras != null) 
        {
        	
        	String sign = extras.getString("sign");
        	signGetData = "Horoscop "+sign;
            
        	//adresa_url
        	String adresa_url = "http://www.zodiac24.ro/rss/horoscop-zilnic.xml";
            
            try 
            {
            	
            	HttpGet getMethod=new HttpGet(adresa_url);
            	HttpClient client = new DefaultHttpClient ();
          
            	ResponseHandler<String> responseHandler=new BasicResponseHandler();
            	
            	// responseBody - content of the retrieved RSS file
      			String responseBody=client.execute(getMethod, responseHandler);   
      			
      			xml = XMLfromString(responseBody);
      			
      			
      		}
            catch (Throwable t) 
            {
      		
            	t.printStackTrace();
      		}
            
           
            try
            {
            	//parsing xml file
            	xmlDataA = parseXML(xml);
            
            	//dialog.dismiss();
            	List<String> values = new ArrayList<String>();
            	
            	// Get a set of the entries
            	Set<Entry<String, String>> set = xmlDataA.entrySet();
            	
            	// Get an iterator
            	Iterator<Entry<String, String>> i = set.iterator();
		
            	// Add elements to the list of values
            	while(i.hasNext()) 
            	{
            		Map.Entry<String, String> me = (Map.Entry<String, String>)i.next();
				
            		values.add(me.getKey() +me.getValue());
				
            	}
			
            	//sort
            	Collections.sort(values);	
			
            	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, values);
			
            	setListAdapter(adapter);
            	}
            
            	//mainly used to catch NullPointerException
            	catch(Exception e)
            	{
            		e.printStackTrace();
            	}
        	}
      
        //Done button
        final Button button = (Button) findViewById(R.id.button);
        /**
         * OnClickListener
         */
        button.setOnClickListener(new OnClickListener() 
        {
            public void onClick(View v) 
            {
            	
                // Perform action on clicks
                Toast.makeText(ReadHoroscopeActivity.this, "Done button clicked", Toast.LENGTH_SHORT).show();
                
            	finish();
            }
        });// end OnClickListener
 
    }
	
	/**
	 * 
	 * @param xml
	 * @return
	 */
	
	private HashMap<String,String> parseXML(Document xml) {
		HashMap<String,String> xmlData = new HashMap<String,String>();
	
		
		for(int t=0;t<12;t++)
		{
			
			NodeList nodes = xml.getElementsByTagName("item");
			
			
			if(signGetData.equals(nodes.item(t).getChildNodes().item(1).getTextContent()))
			{
				// 1 title = "Horoscop" + sign
				xmlData.put("1.",nodes.item(t).getChildNodes().item(1).getTextContent());
				
				// 7 publication date - current day
				xmlData.put("2.Publication date:", nodes.item(t).getChildNodes().item(7).getTextContent().substring(0, 10));
			
				// 9 description
				String txtDescription = nodes.item(t).getChildNodes().item(9).getTextContent().replaceAll("<br />", "");
				
				int startSubString = txtDescription.lastIndexOf("/>")+2;
				String descriptionHoroscope = txtDescription.substring(startSubString);
				descriptionHoroscope.replaceFirst("<br />", "");
				
				xmlData.put("3.", descriptionHoroscope);
			
			}
			
		}// end for tag "item"
		
		return xmlData;
		

	}
	
	/**
	 * 
	 * @param xml
	 * @return
	 */
	public Document XMLfromString(String xml){
		 
	    Document doc = null;
	 
	    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	        try {
	 
	        DocumentBuilder db = dbf.newDocumentBuilder();
	 
	        InputSource is = new InputSource();
	            is.setCharacterStream(new StringReader(xml));
	            doc = db.parse(is);
	 
	        } catch (ParserConfigurationException e) {
	            System.out.println("XML parse error: " + e.getMessage());
	            return null;
	        } catch (SAXException e) {
	            System.out.println("Wrong XML file structure: " + e.getMessage());
	            return null;
	        } catch (IOException e) {
	            System.out.println("I/O exeption: " + e.getMessage());
	            return null;
	        }
	 
	        return doc;
	 
	    }
	

}